import 'dart:developer';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/common/constant/api.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/common/widges/gctabbar.dart';
import 'package:guochaoapp/controller/home/home_controller.dart';
import 'package:guochaoapp/controller/shopping/shopping_controller.dart';
import 'package:guochaoapp/model/mallinit_entity.dart';
import 'package:guochaoapp/model/sku_entity.dart';
import 'package:guochaoapp/model/spu_entity.dart';
import 'package:guochaoapp/r.dart';
import 'package:guochaoapp/services/user_service.dart';

class GCMallController extends GetxController {
  TabController tabar;

  var isFirst = true;
  var mallInitList = RxList<MallinitData>.empty();
  var spuList = RxList<SpuDataSpuList>.empty();
  var skuList = RxList<SkuDataSkuList>.empty();

  List<TextEditingController> textEdittingControllers = [];

  var categorySelectList = [0, 0, 0, 0].obs;
  var categoryId = "";
  var brandId = "";
  var spuId = "";
  var totalPrice = 0.0.obs;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    requestInitData();
  }

  requestInitData() {
    UserService userService = Get.find();

    HttpClient.request<MallinitEntity>(
        url: MallApi.init,
        method: Method.GET,
        params: {"dealerId": userService.dealerId},
        onSuccess: (_, model) async {
          mallInitList.assignAll(model.data);

          brandId = model.data[0].brandList[0].brandId.toString();
          categoryId = model.data[0].categoryList[0].categoryId.toString();
          requestSpuData();

          // if(isFirst) {
          //   GCHomeController homeController = Get.find();
          //   if(homeController.specifyJumpIndex != -1) {
          //     Future.delayed(Duration(milliseconds: 1000)).then((e) {
          //       tabar.animateTo(homeController.specifyJumpIndex);
          //     });
          //     isFirst = false;
          //     homeController.specifyJumpIndex = -1;
          //   }
          // }
        },
        onFailed: (err) async {
          EasyLoading.showError(err);
        });
  }

  requestSpuData() {
    UserService userService = Get.find();

    HttpClient.request<SpuEntity>(
        url: MallApi.spu,
        method: Method.GET,
        params: {
          "dealerId": userService.dealerId,
          "categoryId": categoryId,
          "brandId": brandId,
        },
        onSuccess: (_, model) async {
          spuList.assignAll(model.data.spuList);
          if (model.data.spuList.length > 0) {
            spuId = model.data.spuList[0].spuId.toString();
            requestSkuData();
          } else {
            skuList.removeRange(0, skuList.length);
          }
        },
        onFailed: (err) async {
          EasyLoading.showError(err);
        });
  }

  requestSkuData() {
    UserService userService = Get.find();

    HttpClient.request<SkuEntity>(
        url: MallApi.sku,
        method: Method.GET,
        params: {
          "dealerId": userService.dealerId,
          "categoryId": categoryId,
          "brandId": brandId,
          "spuId": spuId
        },
        onSuccess: (_, model) async {
          textEdittingControllers = model.data.skuList.map((e) {
            var controller = TextEditingController();
            controller.text = "0";
            return controller;
          }).toList();
          totalPrice.value = 0.0;
          skuList.assignAll(model.data.skuList);
        },
        onFailed: (err) async {
          EasyLoading.showError(err);
        });
  }

  firstCategoryItemTap(int itemIndex) {
    if (itemIndex == categorySelectList[0]) return;

    Future.delayed(Duration(milliseconds: 200)).then((e) {
      tabar.animateTo(itemIndex);
    });

    categorySelectList.assignAll([itemIndex, 0, 0, 0]);
    categoryId = mallInitList[categorySelectList[0]]
        .categoryList[0]
        .categoryId
        .toString();
    brandId =
        mallInitList[categorySelectList[0]].brandList[0].brandId.toString();
    clearPrice();
    requestSpuData();
  }

  brandItemTap(int itemIndex) {
    if (itemIndex == categorySelectList[1]) return;
    categorySelectList.assignAll([categorySelectList[0], itemIndex, 0, 0]);
    brandId = mallInitList[categorySelectList[0]]
        .brandList[itemIndex]
        .brandId
        .toString();
    clearPrice();
    requestSpuData();
  }

  secondCategoryItemTap(int itemIndex) {
    if (itemIndex == categorySelectList[2]) return;

    categorySelectList.assignAll(
        [categorySelectList[0], categorySelectList[1], itemIndex, 0]);
    categoryId = mallInitList[categorySelectList[0]]
        .categoryList[itemIndex]
        .categoryId
        .toString();
    clearPrice();
    requestSpuData();
  }

  spuItemTap(int itemIndex) {
    if (categorySelectList[3] == itemIndex) return;
    spuId = spuList[itemIndex].spuId.toString();
    categorySelectList.assignAll([
      categorySelectList[0],
      categorySelectList[1],
      categorySelectList[2],
      itemIndex
    ]);
    clearPrice();
    requestSkuData();
  }

  addNumber(int index) {
    int count = int.parse(textEdittingControllers[index].text);
    count++;
    totalPrice.value += skuList[index].price;
    textEdittingControllers[index].text = count.toString();
  }

  subtractNumber(int index) {
    int count = int.parse(textEdittingControllers[index].text);
    if (count <= 0) {
      return;
    }
    count--;
    totalPrice.value -= skuList[index].price;
    textEdittingControllers[index].text = count.toString();
  }

  caluTotalPrice() {

    var tempTotalPrice = 0.0;
    for(int i = 0; i < skuList.length; i++) {
      var price = skuList[i].price;
      var count = int.parse(textEdittingControllers[i].text);

      tempTotalPrice += price * count;
      textEdittingControllers[i].text = count.toString();
    }

    totalPrice.value = tempTotalPrice;
  }

  addShopping() {
    List<Map> itemList = [];

    var unit = "";
    for (int i = 0; i < textEdittingControllers.length; i++) {
      int count = int.parse(textEdittingControllers[i].text);
      if (count > 0) {
        SkuDataSkuList data = skuList[i];
        unit = data.unit;
        itemList.add({
          "categoryName": data.categoryName,
          "skuSpec": data.skuSpec,
          "num": count,
          "skuId": data.skuId,
          "price": data.price
        });
      }
    }

    if(itemList.length == 0) {
      EasyLoading.showError("未选择商品");
      return;
    }

    showShoppingResult(itemList, unit);
  }

  showShoppingResult(List<Map> mapList, String unit) {
    int totalCount = 0;
    textEdittingControllers.forEach((element) {
      totalCount += int.parse(element.text);
    });

    showDialog(
        context: Get.context,
        barrierDismissible: false,
        builder: (context) {
          return Center(
              child: Container(
            width: 295,
            height: 347,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(8)),
            ),
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Column(children: [
                Row(children: [
                  Text(
                      mallInitList[categorySelectList[0]]
                              .brandList[categorySelectList[1]]
                              .brandName +
                          "/" +
                          mallInitList[categorySelectList[0]]
                              .categoryList[categorySelectList[2]]
                              .categoryName +
                          "/" +
                          spuList[categorySelectList[3]].mallTitle,
                      style: TextStyle(
                          color: Color(0xFF333333),
                          fontSize: 14,
                          fontWeight: FontWeight.bold)),
                  Expanded(child: SizedBox()),
                  GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: Image.asset(R.assetsIconMallTodo,
                          width: 20, height: 20)),
                ]),
                Row(children: [
                  Text("总计:¥" + totalPrice.value.toStringAsFixed(2),
                      style: TextStyle(color: Color(0xFFF75554), fontSize: 12)),
                  Text("（$totalCount）" + unit,
                      style: TextStyle(color: Color(0xFF333333), fontSize: 12)),
                ]),
                Expanded(
                  child: ListView.builder(
                      itemCount: mapList.length,
                      itemBuilder: (context, index) {
                        return Container(
                          padding: EdgeInsets.all(2),
                          height: 29,
                          child: Container(
                            decoration: BoxDecoration(
                              color: Color(0xFFF4F8FE),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2)),
                            ),
                            height: 25,
                            child: Row(children: [
                              SizedBox(width: 8),
                              Text(mapList[index]["skuSpec"],
                                  style: TextStyle(
                                      color: Color(0xFF333333), fontSize: 12)),
                              Expanded(child: SizedBox()),
                              Text(mapList[index]["num"].toString(),
                                  style: TextStyle(
                                      color: Color(0xFF333333), fontSize: 12)),
                              Text(unit,
                                  style: TextStyle(
                                      color: Color(0xFF333333), fontSize: 12)),
                              Expanded(child: SizedBox()),
                              Text(
                                  "小计:¥" +
                                      (mapList[index]["price"] *
                                              mapList[index]["num"])
                                          .toStringAsFixed(2),
                                  style: TextStyle(
                                      color: Color(0xFF333333), fontSize: 12)),
                              SizedBox(width: 10),
                            ]),
                          ),
                        );
                      }),
                ),
                SizedBox(height: 25),
                Container(
                  width: double.infinity,
                  child: FlatButton(
                      onPressed: () {
                        UserService userService = Get.find();

                        HttpClient.request(
                            url: MallApi.cart,
                            method: Method.POST,
                            data: {
                              "dealerId": userService.dealerId,
                              "uid": userService.userInfo.uid,
                              "itemList": mapList
                            },
                            onSuccess: (r, _) async {
                              Navigator.pop(context);
                              clearPrice();
                              // GCShoppingController shopping_c = Get.find();
                              // shopping_c.refresh();

                              EasyLoading.showSuccess("添加成功");
                            },
                            onFailed: (err) async {
                              EasyLoading.showError(err);
                            });
                      },
                      color: Theme.of(Get.context).primaryColor,
                      child: Text("添加到购物车",
                          style: TextStyle(color: Colors.white, fontSize: 14))),
                )
              ]),
            ),
          ));
        });
  }

  skuItemTap(int itemIndex) {
    var skuData = skuList[itemIndex];
    showDialog(
        context: Get.context,
        barrierDismissible: false,
        builder: (context) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 272,
                height: 299,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(8)),
                ),
                child: Column(children: [
                  Expanded(
                      child: Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: CachedNetworkImage(imageUrl: skuData.mallLogo),
                  )),
                  SizedBox(height: 5),
                  Container(
                    height: 96,
                    child: Column(children: [
                      Container(
                        height: 20,
                        child: Row(children: [
                          Container(
                            height: 15,
                            child: FlatButton(
                              onPressed: () {},
                              minWidth: 5,
                              color: Color(0xFFE5F3F4),
                              padding: EdgeInsets.only(left: 5, right: 5),
                              shape: RoundedRectangleBorder(
                                side: BorderSide(
                                    color: Theme.of(Get.context).primaryColor,
                                    width: 1,
                                    style: BorderStyle.solid),
                                borderRadius: BorderRadius.circular(3),
                              ),
                              child: Text(
                                skuData.brandName,
                                style: TextStyle(
                                    fontSize: 10,
                                    color: Theme.of(Get.context).primaryColor),
                              ),
                            ),
                          ),
                          SizedBox(width: 1),
                          Text(
                            skuData.categoryName + "/" + skuData.mallTitle,
                            style: TextStyle(
                                fontSize: 12,
                                color: Theme.of(Get.context).primaryColor),
                          ),
                          Expanded(child: SizedBox()),
                          Text(
                            "¥" + skuData.price.toString(),
                            style: TextStyle(
                                fontSize: 16,
                                color: Color(0xFFF75554),
                                fontWeight: FontWeight.bold),
                          ),
                          Text(
                            "/" + skuData.unit,
                            style: TextStyle(
                                fontSize: 10, color: Color(0xFFF75554)),
                          ),
                          SizedBox(width: 12),
                        ]),
                      ),
                      SizedBox(height: 5),
                      Row(
                        children: [
                          SizedBox(width: 10),
                          Text(
                            skuData.skuSpec,
                            style: TextStyle(
                                fontSize: 12,
                                color: Color(0xFF333333),
                                fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                      SizedBox(height: 5),
                      Container(
                        height: 49,
                        width: double.infinity,
                        child: Row(children: [
                          SizedBox(width: 12),
                          Expanded(
                              child: Container(
                                height: 29,
                            decoration: BoxDecoration(
                              color: Color(0xFFF7F7F7),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(3)),
                            ),
                          )),
                          SizedBox(width: 12),
                        ]),
                      )
                    ]),
                  )
                ]),
              ),
              SizedBox(height: 62),
              GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                },
                child: Image.asset(R.assetsIconClose1, width: 36, height: 36),
              )
            ],
          );
        });
  }

  clearPrice() {
    textEdittingControllers.forEach((element) {
      element.text = "0";
    });
    totalPrice.value = 0.0;
  }
}
